package com.lemonfish.controller;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.diboot.core.util.BeanUtils;
import com.diboot.core.vo.JsonResult;
import com.lemonfish.enumcode.CodeEnum;
import com.lemonfish.pojo.dto.UserDTO;
import com.lemonfish.pojo.dto.UserDTOLikeSearch;
import com.lemonfish.pojo.entity.Permission;
import com.lemonfish.pojo.entity.Role;
import com.lemonfish.pojo.entity.User;
import com.lemonfish.pojo.entity.UserRole;
import com.lemonfish.pojo.vo.RoleVO;
import com.lemonfish.pojo.vo.UserVO;
import com.lemonfish.service.RoleService;
import com.lemonfish.service.UserRoleSerivice;
import com.lemonfish.service.UserService;
import com.lemonfish.util.JwtUtil;
import com.lemonfish.util.MyJsonResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

/**
 * User 相关Controller
 *
 * @author Lemonfish
 * @version 1.0
 * @date 2020-03-01
 * Copyright © 张超
 */
@Api(tags = {"User"})
@RequestMapping("/user")
@Slf4j
@RestController
public class UserController extends BaseCrudMappingRestController<User, UserVO> {

    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;
    @Autowired
    private UserRoleSerivice urService;

    /**
     * 登录
     *
     * @param user 前端传来的User对象
     * @return
     */
    @PostMapping("/login")
    public MyJsonResult login(@RequestBody UserDTO user) {
        User target = userService.checkUser(user);
        if (target != null) {
            // 获取带有 role 的 UserVO
            UserVO userVO = userService.getViewObject(target.getId(), UserVO.class);
            // 获取 User相应的 角色RoleVO,RoleVO带有 权限 Permission
            RoleVO roleVO = roleService.getViewObject(userVO.getRole().getId(), RoleVO.class);
            // 获取权限
            List<Permission> permissions = BeanUtils.buildTree(roleVO.getPermissionList());
            // 加权限
            target.setPermissions(permissions);
            String token = JwtUtil.sign(user.getUsername(), user.getPassword());
            int update = userService.update(target.setToken(token));
            if (token != null && update == 1) {
                return MyJsonResult.success(target);
            }
        }
        return MyJsonResult.fail(CodeEnum.FAIL_LOGIN_ERROR);
    }

    /**
     * 获取页面数据
     *
     * @param curPage 当前页码
     * @param size    每页条数
     * @param order   排序
     * @param column  排序的字段
     * @return
     */
    @GetMapping("/{curPage}/{size}")
    public MyJsonResult getUserList(@PathVariable("curPage") long curPage, @PathVariable("size") long size, @RequestParam("order") String order, @RequestParam("orderCol") String column) {
        IPage<User> userList = userService.getUserList(curPage, size, order, column);
        if (userList != null) {
            return MyJsonResult.success(userList);
        } else {
            return MyJsonResult.fail(CodeEnum.FAIL_NOT_FOUND);
        }
    }


    /**
     * 添加
     *
     * @param user
     * @return
     */
    @PostMapping("/insert")
    public MyJsonResult insert(@RequestBody User user) {
        boolean result = userService.createEntity(user);
        if (result) {
            return MyJsonResult.success(null);
        } else {
            return MyJsonResult.fail(CodeEnum.FAIL_OPERATION);
        }
    }

    /**
     * 更新
     *
     * @param user
     * @return
     */
    @PutMapping("/update")
    public MyJsonResult update(@RequestBody User user) {
        int update = userService.update(user);
        System.out.println(update);
        if (update != 0) {
            return MyJsonResult.success(null);
        } else {
            return MyJsonResult.fail(CodeEnum.FAIL_OPERATION);
        }
    }


    /**
     * 删除
     *
     * @param id
     * @return
     */
    @DeleteMapping("/delete/{id}")
    public MyJsonResult delete(@PathVariable("id") int id) {
        boolean result = userService.deleteEntity(id);
        if (result) {
            return MyJsonResult.success(null);
        } else {
            return MyJsonResult.fail(CodeEnum.FAIL_OPERATION);
        }
    }


    /**
     * 模糊查询
     *
     * @param content
     * @return
     */
    @PostMapping("/likeSearch/{curPage}/{pageSize}")
    public MyJsonResult likeSearch(@RequestBody UserDTOLikeSearch content,
                                   @PathVariable("curPage") long curPage,
                                   @PathVariable("pageSize") long pageSize,
                                   @RequestParam("order") String order,
                                   @RequestParam("orderCol") String column) {
        IPage<User> result = userService.getAllByLike(content, curPage, pageSize, order, column);
        return MyJsonResult.success(result);
    }

    @Transactional
    @PutMapping("/{userId}/role/{newRoleId}")
    public MyJsonResult updateRole(@PathVariable("userId") Long userId,
                                   @PathVariable("newRoleId") Long newRoleId) {
        User user = userService.getEntity(userId);
        Role role = roleService.getEntity(newRoleId);

        user.setUpdateTime(new Date());
        user.setRoleName(role.getName());
        userService.update(user);

        System.out.println(newRoleId);

        LambdaQueryWrapper<UserRole> lqw = new LambdaQueryWrapper<>();
        lqw.eq(UserRole::getUserId, userId);

        UserRole ur = urService.getSingleEntity(lqw);
        ur.setRoleId(newRoleId);
        boolean flag = urService.updateEntity(ur);

        return flag ? MyJsonResult.success(true) : MyJsonResult.fail(CodeEnum.FAIL_NOT_FOUND);
    }

    /**
     * 加载更多数据
     *
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "获取关联数据映射关系")
    @GetMapping("/attachMore")
    public JsonResult attachMore(HttpServletRequest request, ModelMap modelMap) throws Exception {
        Wrapper wrapper = null;
        return new JsonResult(modelMap);
    }
}
